<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/blog/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/blog/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/blog/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/blog/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/blog/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/blog/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/blog/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="matplotlib," />





  <link rel="alternate" href="/blog/atom.xml" title="稻草人的编程之路" type="application/atom+xml" />






<meta name="description" content="matplotlib机器学习中一个非常重要的底层可视化库，可视化库很多，但是基本都是以matplotlib为基础 环境 python command client 需要调用show方法才能显示图形  jupyter  使用魔法指令%matplotlib inline，便可以不用调用show方法   本篇文章为了代码展示方便，使用python command client的方式 基础 来个最基础的">
<meta name="keywords" content="matplotlib">
<meta property="og:type" content="article">
<meta property="og:title" content="数据分析之matplotlib">
<meta property="og:url" content="https://wangxiaochuang.github.io/2018/09/18/1.html">
<meta property="og:site_name" content="稻草人的编程之路">
<meta property="og:description" content="matplotlib机器学习中一个非常重要的底层可视化库，可视化库很多，但是基本都是以matplotlib为基础 环境 python command client 需要调用show方法才能显示图形  jupyter  使用魔法指令%matplotlib inline，便可以不用调用show方法   本篇文章为了代码展示方便，使用python command client的方式 基础 来个最基础的">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="https://wangxiaochuang.github.io/blog/2018/09/18/1/1.png">
<meta property="og:image" content="https://wangxiaochuang.github.io/blog/2018/09/18/1/2.png">
<meta property="og:image" content="https://wangxiaochuang.github.io/blog/2018/09/18/1/3.png">
<meta property="og:image" content="https://wangxiaochuang.github.io/blog/2018/09/18/1/4.png">
<meta property="og:image" content="https://wangxiaochuang.github.io/blog/2018/09/18/1/5.png">
<meta property="og:image" content="https://wangxiaochuang.github.io/blog/2018/09/18/1/6.png">
<meta property="og:image" content="https://wangxiaochuang.github.io/blog/2018/09/18/1/7.png">
<meta property="og:image" content="https://wangxiaochuang.github.io/blog/2018/09/18/1/8.png">
<meta property="og:image" content="https://wangxiaochuang.github.io/blog/2018/09/18/1/9.png">
<meta property="og:image" content="https://wangxiaochuang.github.io/blog/2018/09/18/1/10.png">
<meta property="og:image" content="https://wangxiaochuang.github.io/blog/2018/09/18/1/11.png">
<meta property="og:image" content="https://wangxiaochuang.github.io/blog/2018/09/18/1/12.png">
<meta property="og:image" content="https://wangxiaochuang.github.io/blog/2018/09/18/1/13.png">
<meta property="og:image" content="https://wangxiaochuang.github.io/blog/2018/09/18/1/14.png">
<meta property="og:image" content="https://wangxiaochuang.github.io/blog/2018/09/18/1/15.png">
<meta property="og:image" content="https://wangxiaochuang.github.io/blog/2018/09/18/1/16.png">
<meta property="og:image" content="https://wangxiaochuang.github.io/blog/2018/09/18/1/17.png">
<meta property="og:image" content="https://wangxiaochuang.github.io/blog/2018/09/18/1/18.png">
<meta property="og:image" content="https://wangxiaochuang.github.io/blog/2018/09/18/1/19.png">
<meta property="og:image" content="https://wangxiaochuang.github.io/blog/2018/09/18/1/20.png">
<meta property="og:image" content="https://wangxiaochuang.github.io/blog/2018/09/18/1/21.png">
<meta property="og:image" content="https://wangxiaochuang.github.io/blog/2018/09/18/1/22.png">
<meta property="og:image" content="https://note.youdao.com/yws/public/resource/23dab1749cda45fe6736628d54177f02/xmlnote/WEBRESOURCE60ec20fe8a8025522d9c6d3a99fa5b2c/17189">
<meta property="og:updated_time" content="2019-01-07T22:36:29.340Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="数据分析之matplotlib">
<meta name="twitter:description" content="matplotlib机器学习中一个非常重要的底层可视化库，可视化库很多，但是基本都是以matplotlib为基础 环境 python command client 需要调用show方法才能显示图形  jupyter  使用魔法指令%matplotlib inline，便可以不用调用show方法   本篇文章为了代码展示方便，使用python command client的方式 基础 来个最基础的">
<meta name="twitter:image" content="https://wangxiaochuang.github.io/blog/2018/09/18/1/1.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/blog/',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://wangxiaochuang.github.io/2018/09/18/1.html"/>





  <title>数据分析之matplotlib | 稻草人的编程之路</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/blog/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">稻草人的编程之路</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">众人皆醉我独醒 举世皆浊我独清</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/blog/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/blog/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://wangxiaochuang.github.io/blog/2018/09/18/1.html">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="jackstraw">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/blog/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="稻草人的编程之路">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">数据分析之matplotlib</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2018-09-18T01:25:47+00:00">
                2018-09-18
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blog/categories/数据分析/" itemprop="url" rel="index">
                    <span itemprop="name">数据分析</span>
                  </a>
                </span>

                
                
                  ， 
                
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blog/categories/数据分析/基础工具/" itemprop="url" rel="index">
                    <span itemprop="name">基础工具</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
              <span class="post-comments-count">
                <span class="post-meta-divider">|</span>
                <span class="post-meta-item-icon">
                  <i class="fa fa-comment-o"></i>
                </span>
                <a href="/blog/2018/09/18/1.html#comments" itemprop="discussionUrl">
                  <span class="post-comments-count valine-comment-count" data-xid="/blog/2018/09/18/1.html" itemprop="commentCount"></span>
                </a>
              </span>
            
          

          
          
             <span id="/blog/2018/09/18/1.html" class="leancloud_visitors" data-flag-title="数据分析之matplotlib">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">阅读次数&#58;</span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h1 id="matplotlib"><a href="#matplotlib" class="headerlink" title="matplotlib"></a>matplotlib</h1><p>机器学习中一个非常重要的底层可视化库，可视化库很多，但是基本都是以matplotlib为基础</p>
<h2 id="环境"><a href="#环境" class="headerlink" title="环境"></a>环境</h2><ol>
<li><p>python command client</p>
<p>需要调用<code>show</code>方法才能显示图形</p>
</li>
<li><p>jupyter</p>
<p> 使用魔法指令<code>%matplotlib inline</code>，便可以不用调用<code>show</code>方法</p>
</li>
</ol>
<p>本篇文章为了代码展示方便，使用<code>python command client</code>的方式</p>
<h2 id="基础"><a href="#基础" class="headerlink" title="基础"></a>基础</h2><ol>
<li><p>来个最基础的</p>
 <figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 一个简单的折线图</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span><span class="keyword">import</span> matplotlib.pyplot <span class="keyword">as</span> plt</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>plt.plot([<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>,<span class="number">4</span>,<span class="number">5</span>], [<span class="number">1</span>,<span class="number">4</span>,<span class="number">9</span>,<span class="number">16</span>,<span class="number">25</span>])</span><br><span class="line">[&lt;matplotlib.lines.Line2D object at <span class="number">0x11e783550</span>&gt;]</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>plt.show()   </span><br><span class="line"><span class="comment"># x、y的取值返回，matplotlib会自动帮我们适应</span></span><br></pre></td></tr></table></figure>
 <img src="/blog/2018/09/18/1/1.png">
</li>
<li><p>让我们在这个简单的图上添加一些标签，指明x、y轴的意义，添加标题、文字</p>
 <figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;&gt;&gt; </span>plt.plot([<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>,<span class="number">4</span>,<span class="number">5</span>], [<span class="number">1</span>,<span class="number">4</span>,<span class="number">9</span>,<span class="number">16</span>,<span class="number">25</span>])</span><br><span class="line">[&lt;matplotlib.lines.Line2D object at <span class="number">0x1202cad68</span>&gt;]</span><br><span class="line"><span class="comment"># 设置xlabel、ylabel、title等都是可以使用fontsize参数指定字体大小的</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>plt.xlabel(<span class="string">'xlabel'</span>, fontsize=<span class="number">16</span>)</span><br><span class="line">Text(<span class="number">0.5</span>,<span class="number">0</span>,<span class="string">'xlabel'</span>)</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>plt.ylabel(<span class="string">'ylabel'</span>)</span><br><span class="line">Text(<span class="number">0</span>,<span class="number">0.5</span>,<span class="string">'ylabel'</span>)</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>plt.title(<span class="string">'jackstraw: -----'</span>)</span><br><span class="line">Text(<span class="number">0.5</span>,<span class="number">1</span>,<span class="string">'jackstraw: -----'</span>)</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>plt.show()</span><br></pre></td></tr></table></figure>
 <img src="/blog/2018/09/18/1/2.png" title="指定各种表识">
 <figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;&gt;&gt; </span>plt.plot([<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>,<span class="number">4</span>,<span class="number">5</span>], [<span class="number">1</span>,<span class="number">4</span>,<span class="number">9</span>,<span class="number">16</span>,<span class="number">25</span>])</span><br><span class="line">[&lt;matplotlib.lines.Line2D object at <span class="number">0x11e90c668</span>&gt;]</span><br><span class="line"><span class="comment"># 添加网格，让我们更清楚得看到数据情况</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>plt.grid(<span class="keyword">True</span>)</span><br><span class="line"><span class="comment"># 在坐标（3.0, 10）的位置添加一段文字</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>plt.text(<span class="number">3.0</span>, <span class="number">10</span>, <span class="string">"i am text"</span>)</span><br><span class="line">Text(<span class="number">3</span>,<span class="number">10</span>,<span class="string">'i am text'</span>)</span><br><span class="line"><span class="comment"># 添加注释，区别于添加文字，我们可以指定箭头</span></span><br><span class="line"><span class="comment"># xy: 箭头的坐标</span></span><br><span class="line"><span class="comment"># xytext: 文字的坐标</span></span><br><span class="line"><span class="comment"># arrowprops: 箭头的属性</span></span><br><span class="line"><span class="comment"># arrowprops(width): 线条宽度</span></span><br><span class="line"><span class="comment"># arrowprops(headlength): 箭头长度</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>plt.annotate(<span class="string">'i am annotate'</span>, xy=(<span class="number">2.0</span>,<span class="number">4</span>), xytext=(<span class="number">2.5</span>,<span class="number">6</span>), arrowprops=dict(facecolor=<span class="string">'black'</span>,shrink=<span class="number">2</span>))</span><br><span class="line">Text(<span class="number">2.5</span>,<span class="number">6</span>,<span class="string">'i am annotate'</span>)</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>plt.show()</span><br></pre></td></tr></table></figure>
 <img src="/blog/2018/09/18/1/3.png" title="添加说明性文字">
</li>
<li><p>让我们改变一下线条的样式，比如虚线、颜色等</p>
 <figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 这里的线条格式省略了 linestyle 参数名，我们同样可以指定颜色</span></span><br><span class="line"><span class="comment"># plt.plot([1,2,3,4,5], [1,4,9,16,25], '--', color='r')</span></span><br><span class="line"><span class="comment"># plt.plot([1,2,3,4,5], [1,4,9,16,25], 'r--')</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>plt.plot([<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>,<span class="number">4</span>,<span class="number">5</span>], [<span class="number">1</span>,<span class="number">4</span>,<span class="number">9</span>,<span class="number">16</span>,<span class="number">25</span>], <span class="string">'--'</span>)</span><br><span class="line">[&lt;matplotlib.lines.Line2D object at <span class="number">0x11e99ccf8</span>&gt;]</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>plt.xlabel(<span class="string">'xlabel'</span>, fontsize=<span class="number">16</span>)</span><br><span class="line">Text(<span class="number">0.5</span>,<span class="number">0</span>,<span class="string">'xlabel'</span>)</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>plt.ylabel(<span class="string">'ylabel'</span>, fontsize=<span class="number">16</span>)</span><br><span class="line">Text(<span class="number">0</span>,<span class="number">0.5</span>,<span class="string">'ylabel'</span>)</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>plt.show()</span><br></pre></td></tr></table></figure>
 <img src="/blog/2018/09/18/1/4.png" title="设置线条的样式">
</li>
<li><p>设置线条风格以及关键点的风格</p>
 <figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;&gt;&gt; </span>x = np.linspace(<span class="number">-10</span>, <span class="number">10</span>)</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>y = np.sin(x)</span><br><span class="line"><span class="comment"># linewidth: 指定线条的宽度</span></span><br><span class="line"><span class="comment"># linestyle: 指定线条风格</span></span><br><span class="line"><span class="comment"># marker: 指定关键点风格</span></span><br><span class="line"><span class="comment"># markerfacecolor: 指定关键点颜色</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>plt.plot(x, y, linewidth=<span class="number">2.0</span>, linestyle=<span class="string">':'</span>, marker=<span class="string">'o'</span>, markerfacecolor=<span class="string">'r'</span>)</span><br><span class="line">[&lt;matplotlib.lines.Line2D object at <span class="number">0x113fa24e0</span>&gt;]</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>plt.show()</span><br><span class="line"><span class="comment"># 除了上面这种直接在plt对象上操作外，我们也可以操作plot函数返回的对象</span></span><br><span class="line"><span class="comment"># line = plt.plot(x,y)</span></span><br><span class="line"><span class="comment"># plt.setp(line, color='r', linewidth=2.0, alpha=0.5, marker='o', markerfacecolor='b')</span></span><br></pre></td></tr></table></figure>
 <img src="/blog/2018/09/18/1/5.png" title="关键点样式">    
</li>
<li><p>控制图形与边缘的间距</p>
 <figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;&gt;&gt; </span>x = np.arange(<span class="number">5</span>)</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>y1 = np.random.randint(<span class="number">10</span>, <span class="number">20</span>, <span class="number">5</span>)</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>y2 = np.random.randint(<span class="number">10</span>, <span class="number">20</span>, <span class="number">5</span>)</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>plt.barh(x, y1, color=<span class="string">'g'</span>, alpha=<span class="number">0.5</span>)</span><br><span class="line">&lt;BarContainer object of <span class="number">5</span> artists&gt;</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>plt.barh(x, -y2, color=<span class="string">'r'</span>, alpha=<span class="number">0.5</span>)</span><br><span class="line">&lt;BarContainer object of <span class="number">5</span> artists&gt;</span><br><span class="line"><span class="comment"># 设置x轴的最小最大值</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>plt.xlim(-max(y2) - <span class="number">5</span>, max(y1) + <span class="number">5</span>)</span><br><span class="line">(<span class="number">-23</span>, <span class="number">23</span>)</span><br><span class="line"><span class="comment"># 设置y轴的最小最大值</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>plt.ylim(min(x) - <span class="number">1</span>, max(x) + <span class="number">2</span>)</span><br><span class="line">(<span class="number">-1</span>, <span class="number">6</span>)</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>plt.show()</span><br></pre></td></tr></table></figure>
 <img src="/blog/2018/09/18/1/6.png" title="边缘距离"> 
</li>
</ol>
<h2 id="进阶"><a href="#进阶" class="headerlink" title="进阶"></a>进阶</h2><p>通过基础的学习，我相信您已经会画一些线条图了，也能设置这些图的一些属性，现在进入进阶篇，让您更加得心应手的画图</p>
<h3 id="子图"><a href="#子图" class="headerlink" title="子图"></a>子图</h3><ol>
<li><p>一张图里画多个图形</p>
 <figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;&gt;&gt; </span>data = np.arange(<span class="number">0</span>,<span class="number">10</span>,<span class="number">0.5</span>)</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>plt.plot(data, data, <span class="string">'r--'</span>)</span><br><span class="line">[&lt;matplotlib.lines.Line2D object at <span class="number">0x1194d90f0</span>&gt;]</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>plt.plot(data, data ** <span class="number">2</span>, <span class="string">'bs'</span>)</span><br><span class="line">[&lt;matplotlib.lines.Line2D object at <span class="number">0x119418fd0</span>&gt;]</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>plt.plot(data, data ** <span class="number">3</span>, <span class="string">'go'</span>)</span><br><span class="line">[&lt;matplotlib.lines.Line2D object at <span class="number">0x115a8fe10</span>&gt;]</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>plt.show()</span><br><span class="line"><span class="comment"># 也可以将各个数据放在一个函数里</span></span><br><span class="line"><span class="comment"># plt.plot(data, data, 'r--', </span></span><br><span class="line"><span class="comment">#          data, data ** 2, 'bs',</span></span><br><span class="line"><span class="comment">#          data, data ** 3, 'go')</span></span><br></pre></td></tr></table></figure>
 <img src="/blog/2018/09/18/1/7.png" title="多线条"> 
</li>
<li><p>画多个子图（方式一）</p>
 <figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;&gt;&gt; </span>x = np.linspace(<span class="number">-10</span>, <span class="number">10</span>)</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>y = np.sin(x)</span><br><span class="line"><span class="comment"># 声明我们要画一个什么排列的图，这里表示两行一列的第一个图</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>plt.subplot(<span class="number">211</span>)</span><br><span class="line">&lt;matplotlib.axes._subplots.AxesSubplot object at <span class="number">0x1194e3780</span>&gt;</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>plt.plot(x, y, color=<span class="string">'r'</span>)</span><br><span class="line">[&lt;matplotlib.lines.Line2D object at <span class="number">0x114fb9320</span>&gt;]</span><br><span class="line"><span class="comment"># 声明我们要画一个什么排列的图，这里表示两行一列的第二个图</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>plt.subplot(<span class="number">212</span>)</span><br><span class="line">&lt;matplotlib.axes._subplots.AxesSubplot object at <span class="number">0x114fb98d0</span>&gt;</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>plt.plot(x, y, color=<span class="string">'b'</span>)</span><br><span class="line">[&lt;matplotlib.lines.Line2D object at <span class="number">0x114fe2ef0</span>&gt;]</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>plt.show()</span><br></pre></td></tr></table></figure>
 <img src="/blog/2018/09/18/1/8.png" title="子图一"> 
</li>
<li><p>画多个子图（方式二）</p>
 <figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 除了上面这种画子图的方式，还有一种常见的方式</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>fig, axes = plt.subplots(ncols=<span class="number">2</span>)</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>v_bars = axes[<span class="number">0</span>].scatter(x, y, color=<span class="string">'r'</span>)</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>h_bars = axes[<span class="number">1</span>].barh(x, y, color=<span class="string">'b'</span>)</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>fig.show()</span><br></pre></td></tr></table></figure>
 <img src="/blog/2018/09/18/1/9.png" title="子图二"> 
</li>
</ol>
<h3 id="风格设置"><a href="#风格设置" class="headerlink" title="风格设置"></a>风格设置</h3><p>每个图形如果都需要我们自己去设置样式，是一件比较费时的事情，因此matplot帮我们内置了一些风格样式，我们可以直接拿来用，如果对图形风格要求不高，则可以使用</p>
<ol>
<li><p>通过<code>plt.style.available</code>，我们能看到matplot帮我们内置了很多风格</p>
 <figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line">seaborn-dark</span><br><span class="line">seaborn-darkgrid</span><br><span class="line">seaborn-ticks</span><br><span class="line">fivethirtyeight</span><br><span class="line">seaborn-whitegrid</span><br><span class="line">classic</span><br><span class="line">_classic_test</span><br><span class="line">fast</span><br><span class="line">seaborn-talk</span><br><span class="line">seaborn-dark-palette</span><br><span class="line">seaborn-bright</span><br><span class="line">seaborn-pastel</span><br><span class="line">grayscale</span><br><span class="line">seaborn-notebook</span><br><span class="line">ggplot</span><br><span class="line">seaborn-colorblind</span><br><span class="line">seaborn-muted</span><br><span class="line">seaborn</span><br><span class="line">Solarize_Light2</span><br><span class="line">seaborn-paper</span><br><span class="line">bmh</span><br><span class="line">tableau-colorblind10</span><br><span class="line">seaborn-white</span><br><span class="line">dark_background</span><br><span class="line">seaborn-poster</span><br><span class="line">seaborn-deep</span><br></pre></td></tr></table></figure>
</li>
<li><p>使用系统风格</p>
 <figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;&gt;&gt; </span>x = np.linspace(<span class="number">-10</span>, <span class="number">10</span>)</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>y = np.sin(x)</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>plt.plot(x, y)</span><br><span class="line">[&lt;matplotlib.lines.Line2D object at <span class="number">0x116f8b780</span>&gt;]</span><br><span class="line"><span class="comment"># plt.show()</span></span><br><span class="line"><span class="comment"># 指定要使用的样式，后续所有都图形都将使用新的样式风格</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>plt.style.use(<span class="string">'dark_background'</span>)</span><br><span class="line"><span class="comment"># 对比一下调用新风格前后的差别</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>plt.plot(x, y)</span><br><span class="line">[&lt;matplotlib.lines.Line2D object at <span class="number">0x116f8b780</span>&gt;]</span><br><span class="line"><span class="comment"># plt.show()</span></span><br></pre></td></tr></table></figure>
</li>
<li><p>一个特别的风格</p>
 <figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;&gt;&gt; </span>x = np.linspace(<span class="number">-10</span>, <span class="number">10</span>)</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>y = np.sin(x)</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>plt.xkcd()</span><br><span class="line">&lt;matplotlib.rc_context object at <span class="number">0x11787c4e0</span>&gt;</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>plt.plot(x, y)</span><br><span class="line">[&lt;matplotlib.lines.Line2D object at <span class="number">0x1178c8320</span>&gt;]</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>plt.show()</span><br></pre></td></tr></table></figure>
 <img src="/blog/2018/09/18/1/10.png" title="一个特别的风格"> 
</li>
</ol>
<h3 id="不同类型的图"><a href="#不同类型的图" class="headerlink" title="不同类型的图"></a>不同类型的图</h3><h4 id="条形图"><a href="#条形图" class="headerlink" title="条形图"></a>条形图</h4><ol>
<li><p>基本条形图</p>
 <figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;&gt;&gt; </span>np.random.seed(<span class="number">0</span>)</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>x = np.arange(<span class="number">5</span>)</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>y = np.random.randint(<span class="number">-5</span>,<span class="number">5</span>,<span class="number">5</span>)</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>fig, axes = plt.subplots(ncols=<span class="number">2</span>)</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>v_bars = axes[<span class="number">0</span>].bar(x, y, color=<span class="string">'r'</span>)</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>h_bars = axes[<span class="number">1</span>].barh(x, y, color=<span class="string">'b'</span>)</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>fig.show()</span><br></pre></td></tr></table></figure>
 <img src="/blog/2018/09/18/1/11.png" title="一个简单的条形图">
</li>
<li><p>对于条形图，一般有一些分界线，比如正负值的分界点0，我们现在要添加一条线来加强这个分界线的区分</p>
 <figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 在第一个例子的基础上，添加两个调用</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>fig, axes = plt.subplots(ncols=<span class="number">2</span>)</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>x = np.arange(<span class="number">5</span>)</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>y = np.random.randint(<span class="number">-5</span>,<span class="number">5</span>,<span class="number">5</span>)</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>fig, axes = plt.subplots(ncols=<span class="number">2</span>)</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>v_bars = axes[<span class="number">0</span>].bar(x, y, color=<span class="string">'r'</span>)</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>h_bars = axes[<span class="number">1</span>].barh(x, y, color=<span class="string">'b'</span>)</span><br><span class="line"><span class="comment"># 第0个图是竖着的bar图，因此线条应该是横向的</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>axes[<span class="number">0</span>].axhline(<span class="number">0</span>, color=<span class="string">'grey'</span>, linewidth=<span class="number">2</span>)   </span><br><span class="line">&lt;matplotlib.lines.Line2D object at <span class="number">0x11afc49e8</span>&gt;</span><br><span class="line"><span class="comment"># 第1个图是横着的bar图，因此线条应该是竖着的</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>axes[<span class="number">1</span>].axvline(<span class="number">0</span>, color=<span class="string">'grey'</span>, linewidth=<span class="number">2</span>)   </span><br><span class="line">&lt;matplotlib.lines.Line2D object at <span class="number">0x11afe3278</span>&gt;</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>fig.show()</span><br></pre></td></tr></table></figure>
 <img src="/blog/2018/09/18/1/12.png" title="带分界线的条形图">
</li>
<li><p>根据条形图对应单位高度，设置不同颜色</p>
 <figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;&gt;&gt; </span>np.random.seed(<span class="number">0</span>)</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>x = np.arange(<span class="number">5</span>)</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>y = np.random.randint(<span class="number">-5</span>,<span class="number">5</span>,<span class="number">5</span>)</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>fig, ax = plt.subplots()</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>v_bars = ax.bar(x, y, color=<span class="string">'lightblue'</span>)</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span><span class="keyword">for</span> bar <span class="keyword">in</span> v_bars:</span><br><span class="line"><span class="meta">... </span>    print(bar)</span><br><span class="line">...</span><br><span class="line">Rectangle(xy=(<span class="number">-0.4</span>, <span class="number">0</span>), width=<span class="number">0.8</span>, height=<span class="number">0</span>, angle=<span class="number">0</span>)</span><br><span class="line">Rectangle(xy=(<span class="number">0.6</span>, <span class="number">0</span>), width=<span class="number">0.8</span>, height=<span class="number">-5</span>, angle=<span class="number">0</span>)</span><br><span class="line">Rectangle(xy=(<span class="number">1.6</span>, <span class="number">0</span>), width=<span class="number">0.8</span>, height=<span class="number">-2</span>, angle=<span class="number">0</span>)</span><br><span class="line">Rectangle(xy=(<span class="number">2.6</span>, <span class="number">0</span>), width=<span class="number">0.8</span>, height=<span class="number">-2</span>, angle=<span class="number">0</span>)</span><br><span class="line">Rectangle(xy=(<span class="number">3.6</span>, <span class="number">0</span>), width=<span class="number">0.8</span>, height=<span class="number">2</span>, angle=<span class="number">0</span>)</span><br><span class="line"><span class="comment"># 可以看到这个v_bars对象就表示条形图的柱子的集合，我们调整每一个柱子的样式</span></span><br><span class="line"><span class="comment"># 比如下面，我们将值小于零的柱子进行特别设置</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span><span class="keyword">for</span> bar <span class="keyword">in</span> v_bars:</span><br><span class="line"><span class="meta">... </span>    <span class="keyword">if</span> bar.get_height() &lt; <span class="number">0</span>:</span><br><span class="line"><span class="meta">... </span>            bar.set(edgecolor=<span class="string">'darkred'</span>, color=<span class="string">'green'</span>, linewidth=<span class="number">3</span>)</span><br><span class="line">...</span><br><span class="line">[<span class="keyword">None</span>, <span class="keyword">None</span>, <span class="keyword">None</span>]</span><br><span class="line">[<span class="keyword">None</span>, <span class="keyword">None</span>, <span class="keyword">None</span>]</span><br><span class="line">[<span class="keyword">None</span>, <span class="keyword">None</span>, <span class="keyword">None</span>]</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>fig.show()</span><br></pre></td></tr></table></figure>
 <img src="/blog/2018/09/18/1/13.png" title="带分界线的条形图">
</li>
<li><p>（非条形图）填充图</p>
 <figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;&gt;&gt; </span>x = np.random.randn(<span class="number">100</span>).cumsum()</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>y = np.linspace(<span class="number">0</span>, <span class="number">9</span>, <span class="number">100</span>)</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>fig, ax = plt.subplots()</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>ax.fill_between(x, y, color=<span class="string">'lightblue'</span>)</span><br><span class="line">&lt;matplotlib.collections.PolyCollection object at <span class="number">0x11517a470</span>&gt;</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>fig.show()</span><br></pre></td></tr></table></figure>
 <img src="/blog/2018/09/18/1/14.png" title="填充">
</li>
<li><p>（非条形图）复杂一点的填充图</p>
 <figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 再举一个复杂点的填充的例子，好好理解一下，自己删除些参数再看看变化，比如下面这个fill_between函数有两个y，与上面的例子又有何区别</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>x = np.linspace(<span class="number">0</span>, <span class="number">10</span>, <span class="number">200</span>)</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>y1 = <span class="number">2</span> * x + <span class="number">1</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>y2 = <span class="number">3</span> * x + <span class="number">1.2</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>y_mean = <span class="number">0.5</span> * x * np.cos(<span class="number">2</span> * x) + <span class="number">2.5</span> * x + <span class="number">1.1</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>fig, ax = plt.subplots()</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>ax.fill_between(x, y1, y2, color=<span class="string">'red'</span>)</span><br><span class="line">&lt;matplotlib.collections.PolyCollection object at <span class="number">0x1151cd978</span>&gt;</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>ax.plot(x, y1, color=<span class="string">'r'</span>)</span><br><span class="line">[&lt;matplotlib.lines.Line2D object at <span class="number">0x114f205c0</span>&gt;]</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>ax.plot(x, y_mean, color=<span class="string">'black'</span>)</span><br><span class="line">[&lt;matplotlib.lines.Line2D object at <span class="number">0x1151cdcf8</span>&gt;]</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>ax.plot(x, y2, color=<span class="string">'r'</span>)</span><br><span class="line">[&lt;matplotlib.lines.Line2D object at <span class="number">0x1151cd908</span>&gt;]</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>fig.show()</span><br></pre></td></tr></table></figure>
 <img src="/blog/2018/09/18/1/15.png" title="复杂填充">
</li>
<li><p>使用误差棒</p>
 <figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;&gt;&gt; </span>x = np.arange(<span class="number">5</span>)</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>y = np.random.randint(<span class="number">2</span>, <span class="number">4</span>, <span class="number">5</span>)</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>err = [<span class="number">0.1</span>, <span class="number">0.2</span>, <span class="number">0.3</span>, <span class="number">0.4</span>, <span class="number">0.5</span>]</span><br><span class="line"><span class="comment"># 通过yerr指定误差棒数组</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>plt.bar(x, y, yerr=err, alpha=<span class="number">0.3</span>)</span><br><span class="line">&lt;BarContainer object of <span class="number">5</span> artists&gt;</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>plt.ylabel(<span class="string">'variable y'</span>)</span><br><span class="line">Text(<span class="number">0</span>,<span class="number">0.5</span>,<span class="string">'variable y'</span>)</span><br><span class="line"><span class="comment"># 这里在每个x的坐标位置添加对应的标签</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>plt.xticks(x, [<span class="string">'label1'</span>, <span class="string">'label2'</span>, <span class="string">'label3'</span>, <span class="string">'label4'</span>, <span class="string">'label5'</span>])</span><br><span class="line">([&lt;matplotlib.axis.XTick object at <span class="number">0x115213f60</span>&gt;, &lt;matplotlib.axis.XTick object at <span class="number">0x115213898</span>&gt;, &lt;m</span><br><span class="line">atplotlib.axis.XTick object at <span class="number">0x1152135f8</span>&gt;, &lt;matplotlib.axis.XTick object at <span class="number">0x11526a748</span>&gt;, &lt;matpl</span><br><span class="line">otlib.axis.XTick object at <span class="number">0x11526ac18</span>&gt;], &lt;a list of <span class="number">5</span> Text xticklabel objects&gt;)</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>plt.show()</span><br></pre></td></tr></table></figure>
 <img src="/blog/2018/09/18/1/16.png" title="复杂填充">
</li>
<li><p>画一个背靠背的对比条形图</p>
 <figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;&gt;&gt; </span>x = np.arange(<span class="number">5</span>)</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>y1 = np.random.randint(<span class="number">10</span>, <span class="number">20</span>, <span class="number">5</span>)</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>y2 = np.random.randint(<span class="number">10</span>, <span class="number">20</span>, <span class="number">5</span>)</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>plt.barh(x, y1, color=<span class="string">'g'</span>, alpha=<span class="number">0.5</span>)</span><br><span class="line">&lt;BarContainer object of <span class="number">5</span> artists&gt;</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>plt.barh(x, -y2, color=<span class="string">'r'</span>, alpha=<span class="number">0.5</span>)</span><br><span class="line">&lt;BarContainer object of <span class="number">5</span> artists&gt;</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>plt.xlim(-max(y2) - <span class="number">5</span>, max(y1) + <span class="number">5</span>)</span><br><span class="line">(<span class="number">-23</span>, <span class="number">24</span>)</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>plt.ylim(min(x) - <span class="number">1</span>, max(x) + <span class="number">2</span>)</span><br><span class="line">(<span class="number">-1</span>, <span class="number">6</span>)</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>plt.show()</span><br></pre></td></tr></table></figure>
 <img src="/blog/2018/09/18/1/17.png" title="背靠背条形图">
</li>
<li><p>我们经常看到一张图里分了多个组，可以很直观得看到不同组的区别，试验一下结果就知道我说得是什么意思啦</p>
 <figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;&gt;&gt; </span>green_data = np.random.randint(<span class="number">1</span>,<span class="number">10</span>,<span class="number">3</span>)</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>blue_data = np.random.randint(<span class="number">1</span>,<span class="number">10</span>,<span class="number">3</span>)</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>red_data = np.random.randint(<span class="number">1</span>,<span class="number">10</span>,<span class="number">3</span>)</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>pos = np.arange(<span class="number">3</span>)</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>width = <span class="number">0.2</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>fig, ax = plt.subplots(figsize=(<span class="number">8</span>, <span class="number">6</span>))</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>plt.bar(pos, green_data, width, alpha=<span class="number">0.5</span>, color=<span class="string">'g'</span>)</span><br><span class="line">&lt;BarContainer object of <span class="number">3</span> artists&gt;</span><br><span class="line"><span class="comment"># x的坐标需要依次往后挪动一定距离</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>plt.bar([p + width <span class="keyword">for</span> p <span class="keyword">in</span> pos], blue_data, width, alpha=<span class="number">0.5</span>, color=<span class="string">'b'</span>)</span><br><span class="line">&lt;BarContainer object of <span class="number">3</span> artists&gt;</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>plt.bar([p + width * <span class="number">2</span> <span class="keyword">for</span> p <span class="keyword">in</span> pos], red_data, width, alpha=<span class="number">0.5</span>, color=<span class="string">'r'</span>)</span><br><span class="line">&lt;BarContainer object of <span class="number">3</span> artists&gt;</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>fig.show()</span><br><span class="line"><span class="comment"># 自己试验一下设置xlim与ylim，让结果更好看些</span></span><br></pre></td></tr></table></figure>
 <img src="/blog/2018/09/18/1/18.png" title="分组">
</li>
<li><p>在上面例子的基础上，我想在每个bar上都标注上对应的值</p>
 <figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;&gt;&gt; </span>green_data = np.random.randint(<span class="number">1</span>,<span class="number">10</span>,<span class="number">3</span>)</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>blue_data = np.random.randint(<span class="number">1</span>,<span class="number">10</span>,<span class="number">3</span>)</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>pos = np.arange(<span class="number">3</span>)</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>red_data = np.random.randint(<span class="number">1</span>,<span class="number">10</span>,<span class="number">3</span>)</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>width = <span class="number">0.2</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>fig, ax = plt.subplots(figsize=(<span class="number">8</span>, <span class="number">6</span>))</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>green_bars = plt.bar(pos, green_data, width, alpha=<span class="number">0.5</span>, color=<span class="string">'g'</span>)</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span><span class="keyword">for</span> bar <span class="keyword">in</span> green_bars:</span><br><span class="line"><span class="meta">... </span>    height = bar.get_height()</span><br><span class="line"><span class="meta">... </span>    plt.text(bar.get_x()+width/<span class="number">2</span>, height*(<span class="number">1.02</span>), height)</span><br><span class="line">...</span><br><span class="line">Text(<span class="number">0</span>,<span class="number">2.04</span>,<span class="string">'2'</span>)</span><br><span class="line">Text(<span class="number">1</span>,<span class="number">4.08</span>,<span class="string">'4'</span>)</span><br><span class="line">Text(<span class="number">2</span>,<span class="number">9.18</span>,<span class="string">'9'</span>)</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>blue_bars = plt.bar([p + width <span class="keyword">for</span> p <span class="keyword">in</span> pos], blue_data, width, alpha=<span class="number">0.5</span>, color=<span class="string">'b'</span>)</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span><span class="keyword">for</span> bar <span class="keyword">in</span> blue_bars:</span><br><span class="line"><span class="meta">... </span>    height = bar.get_height()</span><br><span class="line"><span class="meta">... </span>    plt.text(bar.get_x()+width/<span class="number">2</span>, height*(<span class="number">1.02</span>), height)</span><br><span class="line">...</span><br><span class="line">Text(<span class="number">0.2</span>,<span class="number">5.1</span>,<span class="string">'5'</span>)</span><br><span class="line">Text(<span class="number">1.2</span>,<span class="number">5.1</span>,<span class="string">'5'</span>)</span><br><span class="line">Text(<span class="number">2.2</span>,<span class="number">8.16</span>,<span class="string">'8'</span>)</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>red_bars = plt.bar([p + width * <span class="number">2</span> <span class="keyword">for</span> p <span class="keyword">in</span> pos], red_data, width, alpha=<span class="number">0.5</span>, color=<span class="string">'r'</span>)</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span><span class="keyword">for</span> bar <span class="keyword">in</span> red_bars:</span><br><span class="line"><span class="meta">... </span>    height = bar.get_height()</span><br><span class="line"><span class="meta">... </span>    plt.text(bar.get_x()+width/<span class="number">2</span>, height*(<span class="number">1.02</span>), height)</span><br><span class="line">...</span><br><span class="line">Text(<span class="number">0.4</span>,<span class="number">6.12</span>,<span class="string">'6'</span>)</span><br><span class="line">Text(<span class="number">1.4</span>,<span class="number">8.16</span>,<span class="string">'8'</span>)</span><br><span class="line">Text(<span class="number">2.4</span>,<span class="number">6.12</span>,<span class="string">'6'</span>)</span><br><span class="line">plt.show()</span><br></pre></td></tr></table></figure>
 <img src="/blog/2018/09/18/1/19.png">
</li>
<li><p>这里我们再举一个例子，我要画一个横着的条形图，这个图的x值都是正数，我要算出一个相对最小值百分比放在每个bar上，并且画一条竖线</p>
 <figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;&gt;&gt; </span>data = range(<span class="number">200</span>, <span class="number">225</span>, <span class="number">5</span>)</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>bar_labels = [<span class="string">'a'</span>, <span class="string">'b'</span>, <span class="string">'c'</span>, <span class="string">'d'</span>, <span class="string">'e'</span>]</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>fig = plt.figure(figsize=(<span class="number">10</span>, <span class="number">8</span>))</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>y_pos = np.arange(len(data))</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>plt.yticks(y_pos, bar_labels, fontsize=<span class="number">16</span>)</span><br><span class="line">([&lt;matplotlib.axis.YTick object at <span class="number">0x124e256d8</span>&gt;, &lt;matplotlib.axis.YTick object at <span class="number">0x124d3ef60</span>&gt;, &lt;m</span><br><span class="line">atplotlib.axis.YTick object at <span class="number">0x124d30f60</span>&gt;, &lt;matplotlib.axis.YTick object at <span class="number">0x124e3b9e8</span>&gt;, &lt;matpl</span><br><span class="line">otlib.axis.YTick object at <span class="number">0x124e3bef0</span>&gt;], &lt;a list of <span class="number">5</span> Text yticklabel objects&gt;)</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>bars = plt.barh(y_pos, data, alpha=<span class="number">0.5</span>, color=<span class="string">'g'</span>)</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>plt.vlines(min(data), <span class="number">-1</span>, len(data) + <span class="number">0.5</span>, linestyles=<span class="string">'dashed'</span>)</span><br><span class="line">&lt;matplotlib.collections.LineCollection object at <span class="number">0x124e450f0</span>&gt;</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span><span class="keyword">for</span> bar <span class="keyword">in</span> bars:</span><br><span class="line"><span class="meta">... </span>    height = bar.get_height()</span><br><span class="line"><span class="meta">... </span>    plt.text(width*<span class="number">1.01</span>, bar.get_y()+height/<span class="number">2</span>, <span class="string">'&#123;0:.2%&#125;'</span>.format(width/min(data)))</span><br><span class="line">...</span><br><span class="line">Text(<span class="number">0.202</span>,<span class="number">0</span>,<span class="string">'0.10%'</span>)</span><br><span class="line">Text(<span class="number">0.202</span>,<span class="number">1</span>,<span class="string">'0.10%'</span>)</span><br><span class="line">Text(<span class="number">0.202</span>,<span class="number">2</span>,<span class="string">'0.10%'</span>)</span><br><span class="line">Text(<span class="number">0.202</span>,<span class="number">3</span>,<span class="string">'0.10%'</span>)</span><br><span class="line">Text(<span class="number">0.202</span>,<span class="number">4</span>,<span class="string">'0.10%'</span>)</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>plt.show()</span><br><span class="line"><span class="comment"># yticks: 用来画刻度</span></span><br><span class="line"><span class="comment"># vlines: 用来画竖线，需要指明x坐标，y最小值，y最大值</span></span><br></pre></td></tr></table></figure>
 <img src="/blog/2018/09/18/1/20.png">
</li>
<li><p>画一个五颜六色的图，每个bar都有一种颜色，而不是上面介绍的同一种颜色</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;&gt;&gt; </span>mean_values = range(<span class="number">10</span>, <span class="number">18</span>)</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>x_pos = range(len(mean_values))</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span><span class="keyword">import</span> matplotlib.colors <span class="keyword">as</span> col</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span><span class="keyword">import</span> matplotlib.cm <span class="keyword">as</span> cm</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>cmap1 = cm.ScalarMappable(col.Normalize(min(mean_values), max(mean_values), cm.hot))</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>cmap2 = cm.ScalarMappable(col.Normalize(<span class="number">0</span>, <span class="number">20</span>, cm.hot))</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>plt.subplot(<span class="number">121</span>)</span><br><span class="line">&lt;matplotlib.axes._subplots.AxesSubplot object at <span class="number">0x12880c940</span>&gt;</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>plt.bar(x_pos, mean_values, color=cmap1.to_rgba(mean_values))</span><br><span class="line">&lt;BarContainer object of <span class="number">8</span> artists&gt;</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>plt.subplot(<span class="number">122</span>)</span><br><span class="line">&lt;matplotlib.axes._subplots.AxesSubplot object at <span class="number">0x1285c8908</span>&gt;</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>plt.bar(x_pos, mean_values, color=cmap2.to_rgba(mean_values))</span><br><span class="line">&lt;BarContainer object of <span class="number">8</span> artists&gt;</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>plt.show()</span><br></pre></td></tr></table></figure>
<img src="/blog/2018/09/18/1/21.png" title="color map">
</li>
<li><p>我想将每个bar的中间部分都填充不同的形状，看代码吧</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;&gt;&gt; </span>patterns = (<span class="string">'-'</span>, <span class="string">'+'</span>, <span class="string">'x'</span>, <span class="string">'\\'</span>, <span class="string">'*'</span>, <span class="string">'o'</span>, <span class="string">'O'</span>, <span class="string">'.'</span>)</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>fig = plt.figure(figsize=(<span class="number">10</span>, <span class="number">8</span>))</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>x_pos = range(len(patterns))</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>mean_values = np.arange(len(patterns)) + <span class="number">1</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>bars = plt.bar(x_pos, mean_values, color=<span class="string">'white'</span>)</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span><span class="keyword">for</span> idx, bar <span class="keyword">in</span> enumerate(bars):</span><br><span class="line"><span class="meta">... </span>    bar.set_hatch(patterns[idx])</span><br><span class="line">...</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>fig.show()</span><br></pre></td></tr></table></figure>
<img src="/blog/2018/09/18/1/22.png" title="hatch">
</li>
</ol>
<h4 id="盒图"><a href="#盒图" class="headerlink" title="盒图"></a>盒图</h4><p>那么什么是盒图呢？<br><img src="https://note.youdao.com/yws/public/resource/23dab1749cda45fe6736628d54177f02/xmlnote/WEBRESOURCE60ec20fe8a8025522d9c6d3a99fa5b2c/17189" alt="盒图"></p>
<blockquote>
<p>Q1: 总的区间的1/4位置<br>Q3: 总的区间的3/4位置<br>IQR: Q3 - Q1<br>离群点: value &lt; Q1 - 1.5 x IQR  and  value&gt; Q3 + 1.5 x IQR</p>
</blockquote>
<ol>
<li><p>知道了概念了，我们来构造一个基础的盒图</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">data = np.random.normal(<span class="number">0</span>, <span class="number">5</span>, <span class="number">100</span>)</span><br><span class="line">plt.boxplot(data)</span><br><span class="line"><span class="comment"># 这个我们构造了一个符合正太分布的数据，并用盒图展现</span></span><br></pre></td></tr></table></figure>
</li>
<li><p>上面的基础例子我们构造的是一组数据，因此就是一个盒图，我们现在多来几组数据</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">data = [np.random.normal(<span class="number">0</span>, std, <span class="number">100</span>) <span class="keyword">for</span> std <span class="keyword">in</span> range(<span class="number">1</span>,<span class="number">4</span>)]</span><br><span class="line">plt.boxplot(data)</span><br></pre></td></tr></table></figure>
</li>
<li><p>在上面的基础上加上针对每个盒图的x轴额的标注</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">data = [np.random.normal(<span class="number">0</span>, std, <span class="number">100</span>) <span class="keyword">for</span> std <span class="keyword">in</span> range(<span class="number">1</span>,<span class="number">4</span>)]</span><br><span class="line">plt.boxplot(data)</span><br><span class="line">plt.xticks(np.arange(len(data)) + <span class="number">1</span>, [<span class="string">'x1'</span>, <span class="string">'x2'</span>, <span class="string">'x3'</span>])        <span class="comment"># 注意这里设置刻度的第一个参数是从1开始的，比如这里是三个图，就是 [1,2,3]</span></span><br></pre></td></tr></table></figure>
</li>
<li><p>我们还可以修改离群点的符号，默认是 +</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">plt.boxplot(data, sym=<span class="string">'s'</span>)</span><br><span class="line"><span class="comment"># 还可以修改样式，设置notch参数为True即可，自行试验吧</span></span><br></pre></td></tr></table></figure>
</li>
<li><p>我们也可以修改盒图的方向，默认是竖着的，我们也可以横着</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">plt.boxplot(data, sym=<span class="string">'s'</span>, vert=<span class="keyword">False</span>)</span><br></pre></td></tr></table></figure>
</li>
<li><p>默认情况，盒图线条是蓝色加红色，我们也同样可以设置颜色，同时盒图的body体同样可以设置颜色</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">data = [np.random.normal(<span class="number">0</span>, std, <span class="number">100</span>) <span class="keyword">for</span> std <span class="keyword">in</span> range(<span class="number">1</span>,<span class="number">4</span>)]</span><br><span class="line">bplots = plt.boxplot(data)</span><br><span class="line">plt.xticks(np.arange(len(data)) + <span class="number">1</span>, [<span class="string">'x1'</span>, <span class="string">'x2'</span>, <span class="string">'x3'</span>])</span><br><span class="line"><span class="keyword">for</span> _, components <span class="keyword">in</span> bplots.items():        <span class="comment"># 这里拿到的bplots是一个字典</span></span><br><span class="line">    <span class="keyword">for</span> line <span class="keyword">in</span> components:</span><br><span class="line">        line.set_color(<span class="string">'black'</span>)             <span class="comment"># 设置线条颜色</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># 这里设置body体的颜色</span></span><br><span class="line"><span class="comment"># 在上面的基础上要做如下修改</span></span><br><span class="line">bplots = plt.boxplot(data, patch_artist=<span class="keyword">True</span>)       <span class="comment"># patch_artist参数必须设置为True才能填充颜色</span></span><br><span class="line">colors = [<span class="string">'pink'</span>, <span class="string">'lightblue'</span>, <span class="string">'lightgreen'</span>]</span><br><span class="line"><span class="keyword">for</span> bplot, color <span class="keyword">in</span> zip(bplots[<span class="string">'boxes'</span>], colors):</span><br><span class="line">    bplot.set_facecolor(color)</span><br></pre></td></tr></table></figure>
</li>
</ol>
<h4 id="小提琴图"><a href="#小提琴图" class="headerlink" title="小提琴图"></a>小提琴图</h4><p>小提琴图与盒图表达的意义是一致的但是小提琴图相对盒图还能表示数据的集中点分布情况<br><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">data = [np.random.normal(<span class="number">0</span>, std, <span class="number">100</span>) <span class="keyword">for</span> std <span class="keyword">in</span> range(<span class="number">1</span>,<span class="number">4</span>)]</span><br><span class="line">vplots = plt.violinplot(data, showmedians=<span class="keyword">True</span>)</span><br><span class="line">plt.xticks(np.arange(len(data)) + <span class="number">1</span>, [<span class="string">'x1'</span>, <span class="string">'x2'</span>, <span class="string">'x3'</span>])</span><br></pre></td></tr></table></figure></p>
<p>这里我们再给你对于小提琴与与盒图的例子<br><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">fig, axes = plt.subplots(nrows=<span class="number">1</span>, ncols=<span class="number">2</span>)</span><br><span class="line">data = [np.random.normal(<span class="number">0</span>, std, <span class="number">100</span>) <span class="keyword">for</span> std <span class="keyword">in</span> range(<span class="number">6</span>, <span class="number">10</span>)]</span><br><span class="line">axes[<span class="number">0</span>].violinplot(data, showmedians=<span class="keyword">True</span>)</span><br><span class="line">axes[<span class="number">0</span>].set_title(<span class="string">'violin plot'</span>)</span><br><span class="line">axes[<span class="number">1</span>].boxplot(data)</span><br><span class="line">axes[<span class="number">1</span>].set_title(<span class="string">'box plot'</span>)</span><br><span class="line"></span><br><span class="line"><span class="keyword">for</span> ax <span class="keyword">in</span> axes:</span><br><span class="line">    ax.yaxis.grid(<span class="keyword">True</span>)</span><br><span class="line"><span class="comment">#     ax.set_xticks([y+1 for y in range(len(data))])</span></span><br><span class="line">plt.setp(axes, xticks=[y+<span class="number">1</span> <span class="keyword">for</span> y <span class="keyword">in</span> range(len(data))], xticklabels=[<span class="string">'x1'</span>, <span class="string">'x2'</span>, <span class="string">'x3'</span>, <span class="string">'x4'</span>])</span><br></pre></td></tr></table></figure></p>
<h4 id="直方图"><a href="#直方图" class="headerlink" title="直方图"></a>直方图</h4><ol>
<li><p>一个基础的直方图</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> math</span><br><span class="line">data = np.random.normal(<span class="number">0</span>, <span class="number">20</span>, <span class="number">1000</span>)</span><br><span class="line">bins = np.arange(math.floor(min(data)), math.ceil(max(data)), <span class="number">5</span>)</span><br><span class="line">plt.hist(data, bins)</span><br></pre></td></tr></table></figure>
</li>
<li><p>上面就一组数据，那如果有两组数据应该怎么画与区分呢</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> random</span><br><span class="line">data1 = [random.gauss(<span class="number">15</span>, <span class="number">10</span>) <span class="keyword">for</span> i <span class="keyword">in</span> range(<span class="number">500</span>)]</span><br><span class="line">data2 = [random.gauss(<span class="number">5</span>, <span class="number">5</span>) <span class="keyword">for</span> i <span class="keyword">in</span> range(<span class="number">500</span>)]</span><br><span class="line">bins = np.arange(<span class="number">-50</span>, <span class="number">50</span>, <span class="number">2.5</span>)</span><br><span class="line">plt.hist(data1, bins=bins, label=<span class="string">'class1'</span>, alpha=<span class="number">0.3</span>)</span><br><span class="line">plt.hist(data2, bins=bins, label=<span class="string">'class2'</span>, alpha=<span class="number">0.3</span>)</span><br><span class="line">plt.legend(loc=<span class="string">'best'</span>)</span><br></pre></td></tr></table></figure>
</li>
</ol>
<h4 id="散点图"><a href="#散点图" class="headerlink" title="散点图"></a>散点图</h4><ol>
<li><p>一个基础的散点图</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">x = np.random.normal(<span class="number">0</span>, <span class="number">1</span>, <span class="number">1000</span>)</span><br><span class="line">y = np.random.normal(<span class="number">0</span>, <span class="number">1</span>, <span class="number">1000</span>)</span><br><span class="line">plt.scatter(x, y, alpha=<span class="number">0.3</span>)</span><br></pre></td></tr></table></figure>
</li>
<li><p>多组数据</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">mu_vec1 = np.array([<span class="number">0</span>, <span class="number">0</span>])</span><br><span class="line">cov_mat1 = np.array([[<span class="number">2</span>,<span class="number">0</span>],[<span class="number">0</span>,<span class="number">2</span>]])</span><br><span class="line"></span><br><span class="line">x1_samples = np.random.multivariate_normal(mu_vec1, cov_mat1, <span class="number">100</span>)</span><br><span class="line">x2_samples = np.random.multivariate_normal(mu_vec1 + <span class="number">0.2</span>, cov_mat1 + <span class="number">0.2</span>, <span class="number">100</span>)</span><br><span class="line">x3_samples = np.random.multivariate_normal(mu_vec1 + <span class="number">0.4</span>, cov_mat1 + <span class="number">0.4</span>, <span class="number">100</span>)</span><br><span class="line">plt.scatter(x1_samples[:,<span class="number">0</span>], x1_samples[:, <span class="number">1</span>], marker=<span class="string">'x'</span>, color=<span class="string">'blue'</span>, alpha=<span class="number">0.6</span>, label=<span class="string">'x1'</span>)     <span class="comment"># 分别传入x数组，y数组</span></span><br><span class="line">plt.scatter(x2_samples[:,<span class="number">0</span>], x2_samples[:, <span class="number">1</span>], marker=<span class="string">'o'</span>, color=<span class="string">'red'</span>, alpha=<span class="number">0.6</span>, label=<span class="string">'x2'</span>)</span><br><span class="line">plt.scatter(x3_samples[:,<span class="number">0</span>], x3_samples[:, <span class="number">1</span>], marker=<span class="string">'^'</span>, color=<span class="string">'green'</span>, alpha=<span class="number">0.6</span>, label=<span class="string">'x3'</span>)</span><br><span class="line">plt.legend(loc=<span class="string">'best'</span>)</span><br></pre></td></tr></table></figure>
</li>
<li><p>对于点不多的情况，我可能要将对应点的坐标写进去</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">x_coords = np.random.rand(<span class="number">10</span>)</span><br><span class="line">y_coords = np.random.rand(<span class="number">10</span>)</span><br><span class="line">plt.scatter(x_coords, y_coords)</span><br><span class="line"><span class="keyword">for</span> x, y <span class="keyword">in</span> zip(x_coords, y_coords):</span><br><span class="line">    plt.annotate(<span class="string">'(%.2f,%.2f)'</span>%(x,y), xy=(x,y), xytext=(<span class="number">0</span>,<span class="number">-15</span>), textcoords=<span class="string">'offset points'</span>, ha=<span class="string">'center'</span>)</span><br><span class="line"><span class="comment"># textcoords: 对于这种画坐标点的要设置该参数，其他不需要，可以自行测试</span></span><br><span class="line"><span class="comment"># xy: 要标记的坐标点</span></span><br><span class="line"><span class="comment"># xytext: 偏移位置</span></span><br><span class="line"><span class="comment"># ha: 对齐方式</span></span><br></pre></td></tr></table></figure>
</li>
<li><p>我们还可以调整点的大小</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">plt.scatter(x_coords, y_coords, s=<span class="number">50</span>)</span><br></pre></td></tr></table></figure>
</li>
<li><p>通过距离设置点的大小，实现一种黑洞的效果</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">mu_vec1 = np.array([<span class="number">0</span>,<span class="number">0</span>])</span><br><span class="line">cov_mat1 = np.array([[<span class="number">1</span>,<span class="number">0</span>],[<span class="number">0</span>,<span class="number">1</span>]])</span><br><span class="line">X = np.random.multivariate_normal(mu_vec1, cov_mat1, <span class="number">500</span>)</span><br><span class="line">fig = plt.figure(figsize=(<span class="number">8</span>,<span class="number">6</span>))</span><br><span class="line">R = X ** <span class="number">2</span></span><br><span class="line">R_sum = R.sum(axis=<span class="number">1</span>)</span><br><span class="line">plt.scatter(X[:,<span class="number">0</span>], X[:,<span class="number">1</span>], color=<span class="string">'grey'</span>, marker=<span class="string">'o'</span>, s=<span class="number">20</span> * R_sum, alpha=<span class="number">0.5</span>)</span><br></pre></td></tr></table></figure>
</li>
</ol>
<h4 id="3D图"><a href="#3D图" class="headerlink" title="3D图"></a>3D图</h4><p>相比2维图，3维图多了一个包 <code>from mpl_toolkits.mplot3d import Axes3D</code></p>
<ol>
<li><p>一个基本的3D图</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 使用Axes3D函数</span></span><br><span class="line"><span class="keyword">from</span> mpl_toolkits.mplot3d <span class="keyword">import</span> Axes3D</span><br><span class="line">fig = plt.figure()</span><br><span class="line">ax = Axes3D(fig)            <span class="comment"># 将2D转为一个3D</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># 使用gca函数</span></span><br><span class="line"><span class="keyword">from</span> mpl_toolkits.mplot3d <span class="keyword">import</span> Axes3D</span><br><span class="line">fig = plt.figure()</span><br><span class="line">ax = fig.gca(projection=<span class="string">'3d'</span>)</span><br><span class="line"></span><br><span class="line"><span class="comment"># 使用add_subplot</span></span><br><span class="line"><span class="keyword">from</span> mpl_toolkits.mplot3d <span class="keyword">import</span> Axes3D</span><br><span class="line">fig = plt.figure()</span><br><span class="line">ax = fig.add_subplot(<span class="number">111</span>, projection=<span class="string">'3d'</span>)</span><br><span class="line"></span><br><span class="line"><span class="comment"># 总结一下，总之都要拿到ax，然后我们利用ax画图</span></span><br><span class="line"><span class="comment"># 示例一</span></span><br><span class="line">theta = np.linspace(<span class="number">-4</span> * np.pi, <span class="number">4</span> * np.pi, <span class="number">100</span>)</span><br><span class="line">z = np.linspace(<span class="number">-2</span>, <span class="number">2</span>, <span class="number">100</span>)</span><br><span class="line">r = z ** <span class="number">2</span> + <span class="number">1</span></span><br><span class="line">x = r * np.sin(theta)</span><br><span class="line">y = r * np.cos(theta)</span><br><span class="line">ax.plot(x, y, z)</span><br><span class="line"></span><br><span class="line"><span class="comment"># 示例二</span></span><br><span class="line">x = np.arange(<span class="number">-4</span>, <span class="number">4</span>, <span class="number">0.25</span>)</span><br><span class="line">y = np.arange(<span class="number">-4</span>, <span class="number">4</span>, <span class="number">0.25</span>)</span><br><span class="line">X, Y = np.meshgrid(x, y)</span><br><span class="line">Z = np.sin(np.sqrt(X ** <span class="number">2</span> + Y ** <span class="number">2</span>))</span><br><span class="line">ax.plot_surface(X, Y, Z, rstride=<span class="number">1</span>, cstride=<span class="number">1</span>, cmap=<span class="string">'rainbow'</span>)</span><br><span class="line"><span class="comment"># rstride: 行宽度</span></span><br><span class="line"><span class="comment"># cstride: 列宽度</span></span><br></pre></td></tr></table></figure>
</li>
<li><p>画一个三维的包含两组数据的散点图，设置不同颜色</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">x = np.arange(<span class="number">-4</span>, <span class="number">4</span>, <span class="number">0.25</span>)</span><br><span class="line">y = np.arange(<span class="number">-4</span>, <span class="number">4</span>, <span class="number">0.25</span>)</span><br><span class="line">X, Y = np.meshgrid(x, y)</span><br><span class="line">Z = np.sin(np.sqrt(X ** <span class="number">2</span> + Y ** <span class="number">2</span>))</span><br><span class="line">ax.plot_surface(X, Y, Z, rstride=<span class="number">1</span>, cstride=<span class="number">1</span>, cmap=<span class="string">'rainbow'</span>)</span><br></pre></td></tr></table></figure>
</li>
<li><p>三维的图都有一个视角，我们如何改变视角呢</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">ax.view_init(<span class="number">20</span>, <span class="number">0</span>)         <span class="comment"># 参数值决定了视角方向，自己试验吧</span></span><br></pre></td></tr></table></figure>
</li>
<li><p>我们画一个三维的条形图</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">fig = plt.figure()</span><br><span class="line">ax = fig.add_subplot(<span class="number">111</span>, projection=<span class="string">'3d'</span>)</span><br><span class="line"><span class="keyword">for</span> c, z <span class="keyword">in</span> zip([<span class="string">'r'</span>, <span class="string">'g'</span>, <span class="string">'b'</span>, <span class="string">'y'</span>], [<span class="number">30</span>, <span class="number">20</span>, <span class="number">10</span>, <span class="number">0</span>]):</span><br><span class="line">    xs = np.arange(<span class="number">20</span>)</span><br><span class="line">    ys = np.random.rand(<span class="number">20</span>)</span><br><span class="line">    ax.bar(xs, ys, z, zdir=<span class="string">'y'</span>, color=c, alpha=<span class="number">0.5</span>)         <span class="comment"># zdir默认值是z，可能会觉得方向不对，自行调整为y即可</span></span><br></pre></td></tr></table></figure>
</li>
<li><p>画投影</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">fig = plt.figure()</span><br><span class="line">ax = fig.gca(projection=<span class="string">'3d'</span>)</span><br><span class="line">x = np.arange(<span class="number">-4</span>, <span class="number">4</span>, <span class="number">0.25</span>)</span><br><span class="line">y = np.arange(<span class="number">-4</span>, <span class="number">4</span>, <span class="number">0.25</span>)</span><br><span class="line">X, Y = np.meshgrid(x, y)</span><br><span class="line">Z = np.sin(np.sqrt(X ** <span class="number">2</span> + Y ** <span class="number">2</span>))</span><br><span class="line">ax.plot_surface(X, Y, Z, rstride=<span class="number">1</span>, cstride=<span class="number">1</span>, cmap=<span class="string">'rainbow'</span>)</span><br><span class="line">ax.contour(X, Y, Z, offset=<span class="number">-2</span>, cmap=<span class="string">'rainbow'</span>)          <span class="comment"># 画投影</span></span><br><span class="line">ax.set_zlim(<span class="number">-2</span>, <span class="number">2</span>)          <span class="comment"># 设置z的范围</span></span><br></pre></td></tr></table></figure>
</li>
</ol>
<h4 id="pie图"><a href="#pie图" class="headerlink" title="pie图"></a>pie图</h4><ol>
<li><p>一个简单的pie图<br>pie图用于直观得查看比例的</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">m = <span class="number">51212</span></span><br><span class="line">f = <span class="number">40742</span></span><br><span class="line">m_perc = m / (m+f)</span><br><span class="line">f_perc = f / (m+f)</span><br><span class="line">colors = [<span class="string">'navy'</span>, <span class="string">'lightcoral'</span>]</span><br><span class="line">labels = [<span class="string">'Male'</span>, <span class="string">'Female'</span>]</span><br><span class="line">plt.figure(figsize=(<span class="number">8</span>, <span class="number">8</span>))</span><br><span class="line">paches, texts, autotexts = plt.pie([m_perc, f_perc], labels=labels, autopct=<span class="string">'%0.10f%%'</span>, explode=[<span class="number">0</span>, <span class="number">0.1</span>], colors=colors)</span><br><span class="line"><span class="comment"># autopct: 这里的值比较特别，就是表示百分比，可以设置显示精度，偏移大小</span></span><br><span class="line"><span class="comment"># explode: 控制缝隙大小</span></span><br></pre></td></tr></table></figure>
</li>
<li><p>上面的基础图太丑了，我们可以美化一下</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">for</span> text <span class="keyword">in</span> texts + autotexts:</span><br><span class="line">    text.set_fontsize(<span class="number">20</span>)</span><br><span class="line"><span class="keyword">for</span> text <span class="keyword">in</span> autotexts:</span><br><span class="line">    text.set_color(<span class="string">'white'</span>)</span><br><span class="line"><span class="comment"># texts: 表示labels</span></span><br><span class="line"><span class="comment"># autotexts: 表示百分比的文字</span></span><br></pre></td></tr></table></figure>
</li>
</ol>
<h3 id="一些绘图细节设置"><a href="#一些绘图细节设置" class="headerlink" title="一些绘图细节设置"></a>一些绘图细节设置</h3><h4 id="关于轴的设置"><a href="#关于轴的设置" class="headerlink" title="关于轴的设置"></a>关于轴的设置</h4><ol>
<li><p>一个默认的图的轴样式，自行执行查看</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">x = range(<span class="number">10</span>)</span><br><span class="line">y = range(<span class="number">10</span>)</span><br><span class="line">plt.plot(x, y)</span><br></pre></td></tr></table></figure>
</li>
<li><p>现在要将x轴与y轴的刻度去掉</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">x = range(<span class="number">10</span>)</span><br><span class="line">y = range(<span class="number">10</span>)</span><br><span class="line">fig = plt.gca()</span><br><span class="line">plt.plot(x, y)</span><br><span class="line">fig.axes.get_xaxis().set_visible(<span class="keyword">False</span>)</span><br><span class="line">fig.axes.get_yaxis().set_visible(<span class="keyword">False</span>)</span><br></pre></td></tr></table></figure>
</li>
<li><p>我们以直方图的例子，来进行美化</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> math</span><br><span class="line">x = np.random.normal(loc=<span class="number">0.0</span>, scale=<span class="number">1.0</span>, size=<span class="number">300</span>)</span><br><span class="line">width = <span class="number">0.5</span></span><br><span class="line">bins = np.arange(math.floor(x.min())-width, math.ceil(x.max())+width, width)</span><br><span class="line">ax = plt.subplot(<span class="number">111</span>)</span><br><span class="line">ax.spines[<span class="string">'top'</span>].set_visible(<span class="keyword">False</span>)         <span class="comment"># 删除上边的轴线</span></span><br><span class="line">ax.spines[<span class="string">'right'</span>].set_visible(<span class="keyword">False</span>)       <span class="comment"># 删除右边的轴线</span></span><br><span class="line">plt.hist(x, alpha=<span class="number">0.5</span>, bins=bins)</span><br><span class="line"></span><br><span class="line"><span class="comment"># 上面的轴线不见了，但是刻度还在，我们这里看看如何删除刻度</span></span><br><span class="line">plt.tick_params(top=<span class="keyword">False</span>, right=<span class="keyword">False</span>)</span><br><span class="line"><span class="comment"># 网格加上</span></span><br><span class="line">plt.grid(<span class="keyword">True</span>)</span><br></pre></td></tr></table></figure>
</li>
<li><p>有时我们会设置一些x轴的labels，但是这些label特别长，我们需要美化</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 优化前</span></span><br><span class="line">x = range(<span class="number">10</span>)</span><br><span class="line">y = range(<span class="number">10</span>)</span><br><span class="line">labels = [<span class="string">'jackstraw'</span> <span class="keyword">for</span> i <span class="keyword">in</span> range(<span class="number">10</span>)]</span><br><span class="line">fig, ax = plt.subplots()</span><br><span class="line">plt.plot(x, y)</span><br><span class="line">ax.set_xticklabels(labels)</span><br><span class="line"></span><br><span class="line"><span class="comment"># 优化后</span></span><br><span class="line">ax.set_xticklabels(labels, rotation=<span class="number">45</span>, horizontalalignment=<span class="string">'left'</span>)</span><br></pre></td></tr></table></figure>
</li>
<li><p>有时我们画了多条不同颜色的线，我们需要区分各自表达的意义</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line">x = np.arange(<span class="number">10</span>)</span><br><span class="line"><span class="keyword">for</span> i <span class="keyword">in</span> range(<span class="number">1</span>,<span class="number">4</span>):</span><br><span class="line">    plt.plot(x, i * x ** <span class="number">2</span>, label=<span class="string">'Group %d'</span> % i)       <span class="comment"># 后面还可以添加 marker='o' 的参数，自己试验一下有什么不一样</span></span><br><span class="line">plt.legend()        <span class="comment"># 使用这个函数，便会通道对应label值来区分</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># 上面的指示器位置也是可以调整的，有时可能会挡住数据</span></span><br><span class="line">plt.legend(loc=<span class="string">'best'</span>)          <span class="comment"># 自动选择位置</span></span><br><span class="line"><span class="comment"># 也可以自己设定位置</span></span><br><span class="line">plt.legend(loc=<span class="string">'center left'</span>)   <span class="comment"># 自己查找位置</span></span><br><span class="line"><span class="comment"># 也可以指定在图外面</span></span><br><span class="line">plt.legend(loc=<span class="string">'upper center'</span>, bbox_to_anchor=(<span class="number">0.5</span>,<span class="number">1.15</span>), ncol=<span class="number">3</span>)   </span><br><span class="line"><span class="comment"># 竖着盛放</span></span><br><span class="line">plt.legend(loc=<span class="string">'upper center'</span>, bbox_to_anchor=(<span class="number">1.15</span>,<span class="number">1</span>), ncol=<span class="number">1</span>)</span><br><span class="line"><span class="comment"># 如果非要放某个位置，又会挡住图形，可以设置透明度</span></span><br><span class="line">plt.legend(loc=<span class="string">'upper right'</span>, framealpha=<span class="number">0.1</span>)</span><br></pre></td></tr></table></figure>
</li>
<li><p>可以设置全局参数，所有图形都生效</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 比如我们要修改title的字体大小</span></span><br><span class="line"><span class="keyword">import</span> matplotlib <span class="keyword">as</span> mpl</span><br><span class="line">mpl.rcParams[<span class="string">'axes.titlesize'</span>] = <span class="number">30</span></span><br></pre></td></tr></table></figure>
</li>
</ol>
<h4 id="关于子图布局"><a href="#关于子图布局" class="headerlink" title="关于子图布局"></a>关于子图布局</h4><p>布局这一块，在前面的例子我们涉及了一些简单的布局</p>
<p>比如在subplot函数中指定布局参数111便指画一个图，121指画一行两列的第一个图</p>
<p>这种方式比较基础，可定制性比较差，这里我们介绍使用网格布局</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">ax1 = plt.subplot2grid((<span class="number">3</span>,<span class="number">3</span>), (<span class="number">0</span>,<span class="number">0</span>))</span><br><span class="line">ax2 = plt.subplot2grid((<span class="number">3</span>,<span class="number">3</span>), (<span class="number">1</span>,<span class="number">0</span>))</span><br><span class="line">ax3 = plt.subplot2grid((<span class="number">3</span>,<span class="number">3</span>), (<span class="number">0</span>,<span class="number">2</span>), rowspan=<span class="number">3</span>)     <span class="comment"># 指定了位置与所占行数</span></span><br><span class="line">ax4 = plt.subplot2grid((<span class="number">3</span>,<span class="number">3</span>), (<span class="number">2</span>,<span class="number">0</span>), colspan=<span class="number">2</span>)     <span class="comment"># 指定了位置与所占列数</span></span><br><span class="line">ax1 = plt.subplot2grid((<span class="number">3</span>,<span class="number">3</span>), (<span class="number">0</span>,<span class="number">1</span>), rowspan=<span class="number">2</span>)</span><br><span class="line"><span class="comment"># 试验一下吧</span></span><br></pre></td></tr></table></figure>
<p>我们还可以画一个嵌套的图</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">x = np.linspace(<span class="number">0</span>, <span class="number">10</span>, <span class="number">1000</span>)</span><br><span class="line">y1 = x**<span class="number">2</span></span><br><span class="line">y2 = np.sin(x**<span class="number">2</span>)</span><br><span class="line">fig, ax = plt.subplots()</span><br><span class="line">left, bottom, width, height = [<span class="number">0.22</span>, <span class="number">0.45</span>, <span class="number">0.3</span>, <span class="number">0.35</span>]</span><br><span class="line">sub_ax = fig.add_axes([left, bottom, width, height])</span><br><span class="line">ax.plot(x, y1)</span><br><span class="line">sub_ax.plot(x, y2)</span><br></pre></td></tr></table></figure>
<p>使用另外一种画子图的方式</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> mpl_toolkits.axes_grid1.inset_locator <span class="keyword">import</span> inset_axes</span><br><span class="line"></span><br><span class="line">top10_arrivals_countries = [<span class="string">'CANADA'</span>,<span class="string">'MEXICO'</span>,<span class="string">'UNITED\nKINGDOM'</span>,\</span><br><span class="line">                            <span class="string">'JAPAN'</span>,<span class="string">'CHINA'</span>,<span class="string">'GERMANY'</span>,<span class="string">'SOUTH\nKOREA'</span>,\</span><br><span class="line">                            <span class="string">'FRANCE'</span>,<span class="string">'BRAZIL'</span>,<span class="string">'AUSTRALIA'</span>]</span><br><span class="line">top10_arrivals_values = [<span class="number">16.625687</span>, <span class="number">15.378026</span>, <span class="number">3.934508</span>, <span class="number">2.999718</span>,\</span><br><span class="line">                         <span class="number">2.618737</span>, <span class="number">1.769498</span>, <span class="number">1.628563</span>, <span class="number">1.419409</span>,\</span><br><span class="line">                         <span class="number">1.393710</span>, <span class="number">1.136974</span>]</span><br><span class="line">arrivals_countries = [<span class="string">'WESTERN\nEUROPE'</span>,<span class="string">'ASIA'</span>,<span class="string">'SOUTH\nAMERICA'</span>,\</span><br><span class="line">                      <span class="string">'OCEANIA'</span>,<span class="string">'CARIBBEAN'</span>,<span class="string">'MIDDLE\nEAST'</span>,\</span><br><span class="line">                      <span class="string">'CENTRAL\nAMERICA'</span>,<span class="string">'EASTERN\nEUROPE'</span>,<span class="string">'AFRICA'</span>]</span><br><span class="line">arrivals_percent = [<span class="number">36.9</span>,<span class="number">30.4</span>,<span class="number">13.8</span>,<span class="number">4.4</span>,<span class="number">4.0</span>,<span class="number">3.6</span>,<span class="number">2.9</span>,<span class="number">2.6</span>,<span class="number">1.5</span>]</span><br><span class="line"></span><br><span class="line">fig, ax = plt.subplots(figsize=(<span class="number">20</span>, <span class="number">12</span>))</span><br><span class="line">bars = ax.bar(range(<span class="number">10</span>), top10_arrivals_values, color=<span class="string">'blue'</span>)</span><br><span class="line"><span class="keyword">for</span> rect <span class="keyword">in</span> bars:</span><br><span class="line">    height = rect.get_height()</span><br><span class="line">    ax.text(rect.get_x() + rect.get_width()/<span class="number">2</span>, <span class="number">1.02</span>*height, <span class="string">'&#123;:,&#125;'</span>.format(float(height)), ha=<span class="string">'center'</span>, va=<span class="string">'bottom'</span>, fontsize=<span class="number">18</span>)</span><br><span class="line">plt.xticks(range(<span class="number">10</span>), top10_arrivals_countries, fontsize=<span class="number">18</span>)    <span class="comment"># 注意这里修改刻度的位置，如果下载最后面，则修改的是子图的刻度</span></span><br><span class="line">sub_ax = inset_axes(ax, width=<span class="number">6</span>, height=<span class="number">6</span>, loc=<span class="number">5</span>)               <span class="comment"># width与height指定了子图的宽高，loc指定了位置，自己试验吧</span></span><br><span class="line">explode = (<span class="number">0.08</span>, <span class="number">0.08</span>, <span class="number">0.05</span>, <span class="number">0.05</span>,<span class="number">0.05</span>,<span class="number">0.05</span>,<span class="number">0.05</span>,<span class="number">0.05</span>,<span class="number">0.05</span>)</span><br><span class="line">sub_ax.pie(arrivals_percent, labels=arrivals_countries, autopct=<span class="string">'%1.1f%%'</span>, explode=explode) <span class="comment"># 这里画出来的pie字体非常小，文字也不清楚，自己修正一下试试</span></span><br><span class="line"><span class="keyword">for</span> spine <span class="keyword">in</span> ax.spines.values():</span><br><span class="line">    spine.set_visible(<span class="keyword">False</span>)        <span class="comment"># 去掉所有轴</span></span><br></pre></td></tr></table></figure>
<p>matplotlib也可以画图形，要是感兴趣可以关注一下 <code>from matplotlib.patches import Circle, Wedge, Polygon, Ellipse</code></p>
<h2 id="高级篇"><a href="#高级篇" class="headerlink" title="高级篇"></a>高级篇</h2><p>讲了这么多，让我们看看matplot如何与pandas与sklearn结合</p>
<ol>
<li>这里我们构造一个拥有3个指标20个记录的DataFrame，然后看看针对这些数据，我们能够画成什么样的图</li>
</ol>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> pandas <span class="keyword">as</span> pd</span><br><span class="line"><span class="keyword">import</span> numpy <span class="keyword">as</span> np</span><br><span class="line"><span class="keyword">import</span> matplotlib.pyplot <span class="keyword">as</span> plt</span><br><span class="line"></span><br><span class="line">np.random.seed(<span class="number">0</span>)</span><br><span class="line">df = pd.DataFrame(&#123;<span class="string">'Condition 1'</span>: np.random.rand(<span class="number">20</span>),</span><br><span class="line">                  <span class="string">'Condition 2'</span>: np.random.rand(<span class="number">20</span>) * <span class="number">0.9</span>,</span><br><span class="line">                  <span class="string">'Condition 3'</span>: np.random.rand(<span class="number">20</span>) * <span class="number">1.1</span>&#125;)</span><br><span class="line">fig, ax = plt.subplots()            <span class="comment"># 获取画图的面板</span></span><br><span class="line">df.plot.bar(ax=ax)    <span class="comment"># DataFrame直接使用plot对象进行画图，指定面板即可</span></span><br><span class="line"><span class="comment"># 尝试添加一个参数 df.plot.bar(ax=ax, stacked=True)，看看结果吧</span></span><br></pre></td></tr></table></figure>
<ol>
<li><p>上面的例子试验了么？最后一个注释的结果也看到了么？假设我们想要看到没组数据的百分比情况，应该怎么做呢？</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 在上一个的数据基础上</span></span><br><span class="line"><span class="keyword">from</span> matplotlib.ticker <span class="keyword">import</span> FuncFormatter</span><br><span class="line">np.random.seed(<span class="number">0</span>)</span><br><span class="line">df = pd.DataFrame(&#123;<span class="string">'Condition 1'</span>: np.random.rand(<span class="number">20</span>),</span><br><span class="line">                  <span class="string">'Condition 2'</span>: np.random.rand(<span class="number">20</span>) * <span class="number">0.9</span>,</span><br><span class="line">                  <span class="string">'Condition 3'</span>: np.random.rand(<span class="number">20</span>) * <span class="number">1.1</span>&#125;)</span><br><span class="line">df_ratio = df.div(df.sum(axis=<span class="number">1</span>), axis=<span class="number">0</span>)</span><br><span class="line">fig, ax = plt.subplots()</span><br><span class="line">df_ratio.plot.bar(ax=ax, stacked=<span class="keyword">True</span>)</span><br><span class="line">ax.yaxis.set_major_formatter(FuncFormatter(<span class="keyword">lambda</span> y, _: <span class="string">'&#123;:.0%&#125;'</span>.format(y)))</span><br></pre></td></tr></table></figure>
</li>
<li><p>使用sklean的PCA取出重要指标进行绘图</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> pandas <span class="keyword">as</span> pd</span><br><span class="line"><span class="keyword">import</span> numpy <span class="keyword">as</span> np</span><br><span class="line"><span class="keyword">import</span> matplotlib.pyplot <span class="keyword">as</span> plt</span><br><span class="line"><span class="keyword">from</span> sklearn.decomposition <span class="keyword">import</span> PCA</span><br><span class="line"><span class="keyword">from</span> mpl_toolkits.mplot3d <span class="keyword">import</span> Axes3D</span><br><span class="line"><span class="keyword">from</span> sklearn.preprocessing <span class="keyword">import</span> Imputer</span><br><span class="line"></span><br><span class="line">df = pd.read_csv(<span class="string">'titanic_train.csv'</span>)</span><br><span class="line">obj_df = df.select_dtypes(include=[<span class="string">'object'</span>])</span><br><span class="line">df.drop(obj_df.columns, axis=<span class="number">1</span>, inplace=<span class="keyword">True</span>)   <span class="comment"># 我们必须删掉object类型的数据，Imputer才能处理，否则会报错</span></span><br><span class="line">impute = df.DataFrame(Imputer().fit_transform(df))  <span class="comment"># 拿到一个带有缺失值的DataFrame</span></span><br><span class="line">impute.columns = df.columns</span><br><span class="line">imputer.index = df.index</span><br><span class="line"></span><br><span class="line"><span class="comment"># 我们使用是否存活为标签，因此要删除存活标签作为指标</span></span><br><span class="line">features = impute.drop(<span class="string">'Survived'</span>, axis=<span class="number">1</span>)</span><br><span class="line">y = impute[<span class="string">'Survived'</span>]</span><br><span class="line"></span><br><span class="line"><span class="comment"># 开始计算主成分</span></span><br><span class="line">pca = PCA(n_components=<span class="number">3</span>)</span><br><span class="line">X_r = pca.fit_transform(features)</span><br><span class="line"></span><br><span class="line">print(<span class="string">"Explained variance: \nPC1 &#123;:.2%&#125;\nPC2 &#123;:.2%&#125;\nPC3 &#123;:.2%&#125;"</span>.format(pca.explained_variance_ratio_[<span class="number">0</span>],</span><br><span class="line">               pca.explained_variance_ratio_[<span class="number">1</span>],</span><br><span class="line">               pca.explained_variance_ratio_[<span class="number">2</span>]))</span><br><span class="line"></span><br><span class="line"><span class="comment"># 画图</span></span><br><span class="line">fig = plt.figure()</span><br><span class="line">ax = Axes3D(fig)</span><br><span class="line">ax.scatter(X_r[:, <span class="number">0</span>], X_r[:, <span class="number">1</span>], X_r[:, <span class="number">2</span>], c=y, cmap=plt.cm.coolwarm)</span><br><span class="line"></span><br><span class="line">ax.set_xlabel(<span class="string">'PC1'</span>)</span><br><span class="line">ax.set_xlabel(<span class="string">'PC2'</span>)</span><br><span class="line">ax.set_xlabel(<span class="string">'PC3'</span>)</span><br></pre></td></tr></table></figure>
</li>
<li><p>可选的样式</p>
</li>
</ol>
<div class="table-container">
<table>
<thead>
<tr>
<th>字符</th>
<th>类型</th>
<th>字符</th>
<th>类型</th>
</tr>
</thead>
<tbody>
<tr>
<td>‘-‘</td>
<td></td>
<td>‘—‘</td>
<td></td>
</tr>
<tr>
<td>‘-.’</td>
<td></td>
<td>‘:’</td>
<td></td>
</tr>
<tr>
<td>‘.’</td>
<td></td>
<td>‘,’</td>
<td>像素点</td>
</tr>
<tr>
<td>‘o’</td>
<td></td>
<td>‘v’</td>
<td></td>
</tr>
<tr>
<td>‘^’</td>
<td></td>
<td>‘&lt;’</td>
<td></td>
</tr>
<tr>
<td>‘&gt;’</td>
<td></td>
<td>‘1’</td>
<td></td>
</tr>
<tr>
<td>‘2’</td>
<td></td>
<td>‘3’</td>
<td></td>
</tr>
<tr>
<td>‘4’</td>
<td></td>
<td>‘s’</td>
<td></td>
</tr>
<tr>
<td>‘p’</td>
<td></td>
<td>‘*’</td>
<td></td>
</tr>
<tr>
<td>‘h’</td>
<td></td>
<td>‘H’</td>
<td></td>
</tr>
<tr>
<td>‘+’</td>
<td></td>
<td>‘x’</td>
<td></td>
</tr>
<tr>
<td>‘D’</td>
<td></td>
<td>‘d’</td>
<td></td>
</tr>
<tr>
<td>‘_’</td>
<td></td>
<td></td>
<td></td>
</tr>
</tbody>
</table>
</div>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/blog/tags/matplotlib/" rel="tag"># matplotlib</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/blog/2018/09/15/2.html" rel="next" title="数据分析之pandas">
                <i class="fa fa-chevron-left"></i> 数据分析之pandas
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/blog/2018/09/20/1.html" rel="prev" title="数据分析之seaborn">
                数据分析之seaborn <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
    </div>
  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/blog/images/avatar.jpg"
                alt="jackstraw" />
            
              <p class="site-author-name" itemprop="name">jackstraw</p>
              <p class="site-description motion-element" itemprop="description">人生的意义，不在于最终获得了什么，而在于曾经努力追求过什么</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/blog/archives/">
              
                  <span class="site-state-item-count">19</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                
                  <span class="site-state-item-count">22</span>
                  <span class="site-state-item-name">分类</span>
                
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                
                  <span class="site-state-item-count">22</span>
                  <span class="site-state-item-name">标签</span>
                
              </div>
            

          </nav>

          
            <div class="feed-link motion-element">
              <a href="/blog/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#matplotlib"><span class="nav-number">1.</span> <span class="nav-text">matplotlib</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#环境"><span class="nav-number">1.1.</span> <span class="nav-text">环境</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#基础"><span class="nav-number">1.2.</span> <span class="nav-text">基础</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#进阶"><span class="nav-number">1.3.</span> <span class="nav-text">进阶</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#子图"><span class="nav-number">1.3.1.</span> <span class="nav-text">子图</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#风格设置"><span class="nav-number">1.3.2.</span> <span class="nav-text">风格设置</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#不同类型的图"><span class="nav-number">1.3.3.</span> <span class="nav-text">不同类型的图</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#条形图"><span class="nav-number">1.3.3.1.</span> <span class="nav-text">条形图</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#盒图"><span class="nav-number">1.3.3.2.</span> <span class="nav-text">盒图</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#小提琴图"><span class="nav-number">1.3.3.3.</span> <span class="nav-text">小提琴图</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#直方图"><span class="nav-number">1.3.3.4.</span> <span class="nav-text">直方图</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#散点图"><span class="nav-number">1.3.3.5.</span> <span class="nav-text">散点图</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#3D图"><span class="nav-number">1.3.3.6.</span> <span class="nav-text">3D图</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#pie图"><span class="nav-number">1.3.3.7.</span> <span class="nav-text">pie图</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#一些绘图细节设置"><span class="nav-number">1.3.4.</span> <span class="nav-text">一些绘图细节设置</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#关于轴的设置"><span class="nav-number">1.3.4.1.</span> <span class="nav-text">关于轴的设置</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#关于子图布局"><span class="nav-number">1.3.4.2.</span> <span class="nav-text">关于子图布局</span></a></li></ol></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#高级篇"><span class="nav-number">1.4.</span> <span class="nav-text">高级篇</span></a></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2019</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">jackstraw</span>

  
</div>









        
<div class="busuanzi-count">
  <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv">
      <i class="fa fa-user"></i>访问人数
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
      人
    </span>
  

  
    <span class="site-pv">
      <i class="fa fa-eye"></i>总访问量
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
      次
    </span>
  
</div>








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/blog/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/blog/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/blog/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/blog/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/blog/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/blog/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/blog/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/blog/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  










  <script src="//cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
  <script src="//unpkg.com/valine/dist/Valine.min.js"></script>
  
  <script type="text/javascript">
    var GUEST = ['nick','mail','link'];
    var guest = 'nick,mail';
    guest = guest.split(',').filter(item=>{
      return GUEST.indexOf(item)>-1;
    });
    new Valine({
        el: '#comments' ,
        verify: true,
        notify: false,
        appId: 'lQM75w94ggNR0TjX61NLerrg-gzGzoHsz',
        appKey: 'I2wtQ2rd9KtoJmcEOiYG9zqT',
        placeholder: '如需帮助，请留下邮箱',
        avatar:'mm',
        guest_info:guest,
        pageSize:'10' || 10,
    });
    var infoEle = document.querySelector('#comments .info');
    if (infoEle && infoEle.childNodes && infoEle.childNodes.length > 0){
      infoEle.childNodes.forEach(function(item) {
        item.parentNode.removeChild(item);
      });
    }
  </script>



  





  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.4.js"></script>
  <script>AV.initialize("lQM75w94ggNR0TjX61NLerrg-gzGzoHsz", "I2wtQ2rd9KtoJmcEOiYG9zqT");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  

  

  
  

  
  
    <script type="text/x-mathjax-config">
      MathJax.Hub.Config({
        tex2jax: {
          inlineMath: [ ['$','$'], ["\\(","\\)"]  ],
          processEscapes: true,
          skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
        }
      });
    </script>

    <script type="text/x-mathjax-config">
      MathJax.Hub.Queue(function() {
        var all = MathJax.Hub.getAllJax(), i;
        for (i=0; i < all.length; i += 1) {
          all[i].SourceElement().parentNode.className += ' has-jax';
        }
      });
    </script>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.1/latest.js?config=TeX-AMS-MML_HTMLorMML"></script>
  


  

  

</body>
</html>
